import { getListApi, deleteListApi, addOrUpdateApi } from "../../api/manage";

export default {
  namespaced: true,
  state: {
    list: [],
    pages: {
      currentPage: 0,
      pageSize: 10,
      searchValue: "",
      by: "desc",
      order: "id"
    },
    total: 0
  },
  mutations: {
    //修改总页数or数据列表
    setList(state, lists) {
      state.list = JSON.parse(lists.data);
      state.total = lists.total;
      
    },
    //修改分页
    setPages(state, pages) {
      state.pages.currentPage = pages;
    },
    setKeyword(state, val) {
      state.pages.searchValue = val;
    },
    setSort(state, clo) {
      if (clo.order === "ascending") {
        state.pages.by = "asc";
        state.pages.order = "created";
      } else if (clo.order === "descending") {
        state.pages.by = "desc";
        state.pages.order = "created";
      } else {
        state.pages.by = "desc";
        state.pages.order = "id";
      }
    }
  },
  actions: {
    //获取列表
    async getList({ state, commit }) {
      const res = await getListApi(state.pages);
      commit("setList", res);
    },
    //分页
    async paginition({ commit, dispatch }, pages) {
      commit("setPages", pages);
      dispatch("getList");
    },
    //搜索
    async getKeyword({ commit, dispatch }, val) {
      commit("setKeyword", val);
      dispatch("getList");
    },
    //删除
    async getQuestionsDelete({ dispatch }, ids) {
      await deleteListApi(ids);
      dispatch("getList");
    },
    //新增||修改
    async getCommit({ dispatch }, form) {
      await addOrUpdateApi(form);
      dispatch("getList");
    },
    //排序
    async getSort({ commit, dispatch }, val) {
      commit("setSort", val);
      dispatch("getList");
    }
  }
};
